'use client'

import { useEffect, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Eye, Settings, Users } from 'lucide-react'
import { useToast } from '@/hooks/use-toast'

interface Role {
  id: number
  code: string
  name: string
  description: string
  permissions: string
  parsedPermissions: {
    canEditAll: boolean
    canManageUsers: boolean
    canManageRoles: boolean
    dataSourceAccess: string[]
    editableFields?: {
      [tableType: string]: string[]
    }
  }
  created_at: string
}

export default function RolesManagement() {
  const [roles, setRoles] = useState<Role[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedRole, setSelectedRole] = useState<Role | null>(null)
  const [showDetailsDialog, setShowDetailsDialog] = useState(false)
  const { toast } = useToast()

  useEffect(() => {
    loadRoles()
  }, [])

  const loadRoles = async () => {
    try {
      const response = await fetch('/api/admin/roles')
      const data = await response.json()

      if (data.success) {
        setRoles(data.data)
      } else {
        toast({
          title: "错误",
          description: "加载角色数据失败",
          variant: "destructive",
        })
      }
    } catch (error) {
      console.error('加载角色失败:', error)
      toast({
        title: "错误",
        description: "加载角色数据失败",
        variant: "destructive",
      })
    } finally {
      setLoading(false)
    }
  }

  const getRoleColor = (roleCode: string) => {
    const colors: Record<string, string> = {
      'ADMIN': 'bg-red-100 text-red-800',
      'PROCUREMENT': 'bg-blue-100 text-blue-800',
      'DESIGN': 'bg-green-100 text-green-800',
      'MONITORING': 'bg-orange-100 text-orange-800',
      'OPERATIONS': 'bg-purple-100 text-purple-800',
      'VIEWER': 'bg-gray-100 text-gray-800'
    }
    return colors[roleCode] || 'bg-gray-100 text-gray-800'
  }

  const getDataSourceName = (source: string) => {
    const names: Record<string, string> = {
      'P': '采购',
      'E': '设计',
      'M': '监测',
      'O': '建设',
      'C': '施工',
      'R': '运维'
    }
    return names[source] || source
  }

  const showRoleDetails = (role: Role) => {
    setSelectedRole(role)
    setShowDetailsDialog(true)
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/4 mb-6"></div>
          <div className="h-64 bg-gray-200 rounded"></div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">角色管理</h1>
        <p className="text-gray-600">管理系统角色和权限配置</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>系统角色 ({roles.length})</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>角色信息</TableHead>
                <TableHead>权限概览</TableHead>
                <TableHead>数据来源权限</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {roles.map((role) => (
                <TableRow key={role.id}>
                  <TableCell>
                    <div>
                      <div className="flex items-center space-x-2">
                        <Badge className={getRoleColor(role.code)}>
                          {role.name}
                        </Badge>
                        <span className="text-sm text-gray-500">({role.code})</span>
                      </div>
                      <div className="text-sm text-gray-600 mt-1">{role.description}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="space-y-1">
                      {role.parsedPermissions.canEditAll && (
                        <Badge variant="default" className="mr-1">全部编辑</Badge>
                      )}
                      {role.parsedPermissions.canManageUsers && (
                        <Badge variant="secondary" className="mr-1">用户管理</Badge>
                      )}
                      {role.parsedPermissions.canManageRoles && (
                        <Badge variant="secondary" className="mr-1">角色管理</Badge>
                      )}
                      {!role.parsedPermissions.canEditAll && 
                       !role.parsedPermissions.canManageUsers && 
                       !role.parsedPermissions.canManageRoles && (
                        <Badge variant="outline">基础权限</Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      {role.parsedPermissions.dataSourceAccess.map(source => (
                        <Badge key={source} variant="outline" className="text-xs">
                          {getDataSourceName(source)}
                        </Badge>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell>
                    {new Date(role.created_at).toLocaleDateString()}
                  </TableCell>
                  <TableCell>
                    <div className="flex space-x-2">
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => showRoleDetails(role)}
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                      <Button variant="outline" size="sm">
                        <Settings className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* 角色详情对话框 */}
      <Dialog open={showDetailsDialog} onOpenChange={setShowDetailsDialog}>
        <DialogContent className="sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>角色详情 - {selectedRole?.name}</DialogTitle>
          </DialogHeader>
          {selectedRole && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h3 className="text-lg font-medium mb-3">基本信息</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <div className="text-sm font-medium text-gray-600">角色名称</div>
                    <div className="text-sm text-gray-900">{selectedRole.name}</div>
                  </div>
                  <div>
                    <div className="text-sm font-medium text-gray-600">角色代码</div>
                    <div className="text-sm text-gray-900">{selectedRole.code}</div>
                  </div>
                  <div className="col-span-2">
                    <div className="text-sm font-medium text-gray-600">描述</div>
                    <div className="text-sm text-gray-900">{selectedRole.description}</div>
                  </div>
                </div>
              </div>

              {/* 系统权限 */}
              <div>
                <h3 className="text-lg font-medium mb-3">系统权限</h3>
                <div className="space-y-2">
                  <div className="flex items-center space-x-2">
                    <div className={`w-3 h-3 rounded-full ${selectedRole.parsedPermissions.canEditAll ? 'bg-green-500' : 'bg-gray-300'}`}></div>
                    <span className="text-sm">全部编辑权限</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <div className={`w-3 h-3 rounded-full ${selectedRole.parsedPermissions.canManageUsers ? 'bg-green-500' : 'bg-gray-300'}`}></div>
                    <span className="text-sm">用户管理权限</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <div className={`w-3 h-3 rounded-full ${selectedRole.parsedPermissions.canManageRoles ? 'bg-green-500' : 'bg-gray-300'}`}></div>
                    <span className="text-sm">角色管理权限</span>
                  </div>
                </div>
              </div>

              {/* 数据来源权限 */}
              <div>
                <h3 className="text-lg font-medium mb-3">数据来源权限</h3>
                <div className="flex flex-wrap gap-2">
                  {selectedRole.parsedPermissions.dataSourceAccess.map(source => (
                    <Badge key={source} variant="default">
                      {getDataSourceName(source)}
                    </Badge>
                  ))}
                </div>
              </div>

              {/* 可编辑字段 */}
              {selectedRole.parsedPermissions.editableFields && Object.keys(selectedRole.parsedPermissions.editableFields).length > 0 && (
                <div>
                  <h3 className="text-lg font-medium mb-3">可编辑字段</h3>
                  <div className="space-y-3">
                    {Object.entries(selectedRole.parsedPermissions.editableFields).map(([tableType, fields]) => (
                      <div key={tableType}>
                        <div className="text-sm font-medium text-gray-600 mb-1">
                          {tableType === 'base_params' && '基础参数'}
                          {tableType === 'naming' && '命名参数'}
                          {tableType === 'position' && '位置参数'}
                        </div>
                        <div className="flex flex-wrap gap-1">
                          {fields.map(field => (
                            <Badge key={field} variant="outline" className="text-xs">
                              {field}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
